/* 
 * Copyright (C) 2011, WordCards4Me Project - http://code.google.com/p/wordcards4me/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.wordcards4me;

import java.io.InputStreamReader;
import java.util.Vector;

import org.wordcards4me.utils.StringUtils;

public final class Sequence extends Vector {

	private int index;

	public Sequence(InputStreamReader reader) throws Exception {
		loadCardsFromCSVFileImpl(reader);
	}

	public WordCard currentCard() {
		return (WordCard) elementAt(index);
	}

	public WordCard nextCard() {
		index++;
		index %= size();
		return (WordCard) elementAt(index);
	}

	public WordCard previousCard() {
		index--;
		index = index < 0 ? size() - 1 : index;
		return (WordCard) elementAt(index);
	}

	private void loadCardsFromCSVFileImpl(InputStreamReader reader)
			throws Exception {
		try {
			StringBuffer sb = new StringBuffer();
			int chars;
			while ((chars = reader.read()) != -1) {
				sb.append((char) chars);
			}
			String[] lines = StringUtils.split(sb.toString(), "\n");
			for (int ix = 0; ix < lines.length; ix++) {
				String[] snippets = StringUtils.split(lines[ix], ";");
				if(snippets.length > 1) {
				addElement(new WordCard(snippets[0], snippets[1]));
				}
			}
		} finally {
			reader.close();
		}
	}
}
